package logic

import (
	"context"
	"errors"
	"goods/cache"
	"goods/models"

	"goods/goods"
	"goods/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type AddCartLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewAddCartLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AddCartLogic {
	return &AddCartLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *AddCartLogic) AddCart(in *goods.AddCartRequest) (*goods.AddCartResponse, error) {
	// todo: add your logic here and delete this line
	//判断商品是否存在
	var err error
	var g models.Goods
	g.ID = uint(in.GoodsId)
	if err = g.Detail(); err != nil {
		logx.Error("获取商品详情失败")
		return nil, err
	}
	//判断库存是否充足
	stock, _ := cache.GetGoodsStock(int(g.ID))
	if stock < in.Num {
		logx.Error("商品库存不足")
		return nil, errors.New("商品库存不足")
	}
	//判断购物车中是否存在该商品
	if cache.GetCartGoods(int(in.UserId), int(in.GoodsId)) {
		//存在
		err = cache.UpdateCartGoodsNum(int(in.UserId), int(in.GoodsId), int(in.Num))
	} else {
		goodsMap := map[string]interface{}{
			"user_id":  in.UserId,
			"goods_id": in.GoodsId,
			"num":      in.Num,
			"title":    g.GoodsTitle,
			"price":    g.GoodsPrice,
			"cover":    g.GoodsCover,
		}
		err = cache.AddCart(int(in.UserId), int(in.GoodsId), goodsMap)
	}
	if err != nil {
		logx.Error("购物车添加失败")
		return nil, err
	}
	return &goods.AddCartResponse{}, nil
}
